home *** CD-ROM | disk | FTP | other *** search
/ Aminet 48 / Aminet 48 (2002)(GTI - Schatztruhe)[!][Apr 2002].iso / Aminet / text / edit / vim60rt.lha / Vim / vim60 / doc / usr_41.txt < prev    next >
Encoding:
Text File  |  2001-09-26  |  51.9 KB  |  1,574 lines

  1. *usr_41.txt*    For Vim version 6.0.  Last change: 2001 Sep 18
  2.  
  3.              VIM USER MANUAL - by Bram Moolenaar
  4.  
  5.                   Write a Vim script
  6.  
  7.  
  8. The Vim script language is used for the startup vimrc file, syntax files, and
  9. many other things.  This chapter explains the items that can be used in a Vim
  10. script.  There are a lot of them, thus this is a long chapter.
  11.  
  12. |41.1|    Introduction
  13. |41.2|    Variables
  14. |41.3|    Expressions
  15. |41.4|    Conditionals
  16. |41.5|    Executing an expression
  17. |41.6|    Using functions
  18. |41.7|    Defining a function
  19. |41.8|    Various remarks
  20. |41.9|    Writing a plugin
  21. |41.10|    Writing a filetype plugin
  22. |41.11|    Writing a compiler plugin
  23.  
  24.      Next chapter: |usr_42.txt|  Add new menus
  25.  Previous chapter: |usr_40.txt|  Make new commands
  26. Table of contents: |usr_toc.txt|
  27.  
  28. ==============================================================================
  29. *41.1*    Introduction            *vimrc-intro* *vim-script-intro*
  30.  
  31. Your first experience with Vim scripts is the vimrc file.  Vim reads it when
  32. it starts up and executes the commands.  You can set options to values you
  33. prefer.  And you can use any colon command in it (commands that start with a
  34. ":"; these are sometimes referred to as Ex commands or command-line commands).
  35.    Syntax files are also Vim scripts.  As are files that set options for a
  36. specific file type.  A complicated macro can be defined by a separate Vim
  37. script file.  You can think of other uses yourself.
  38.  
  39. Let's start with a simple example: >
  40.  
  41.     :let i = 1
  42.     :while i < 5
  43.     :  echo "count is" i
  44.     :  let i = i + 1
  45.     :endwhile
  46. <
  47.     Note:
  48.     The ":" characters are not really needed here.  You only need to use
  49.     them when you type a command.  In a Vim script file they can be left
  50.     out.  We will use them here anyway to make clear these are colon
  51.     commands and make them stand out from Normal mode commands.
  52.  
  53. The ":let" command assigns a value to a variable.  The generic form is: >
  54.  
  55.     :let {variable} = {expression}
  56.  
  57. In this case the variable name is "i" and the expression is a simple value,
  58. the number one.
  59.    The ":while" command starts a loop.  The generic form is: >
  60.  
  61.     :while {condition}
  62.     :  {statements}
  63.     :endwhile
  64.  
  65. The statements until the matching ":endwhile" are executed for as long as the
  66. condition is true.  The condition used here is the expression "i < 5".  This
  67. is true when the variable i is smaller than five.
  68.    The ":echo" command prints its arguments.  In this case the string "count
  69. is" and the value of the variable i.  Since i is one, this will print:
  70.  
  71.     count is 1 ~
  72.  
  73. Then there is another ":let i =" command.  The value used is the expression "i
  74. + 1".  This adds one to the variable i and assigns the new value to the same
  75. variable.
  76.    The output of the example code is:
  77.  
  78.     count is 1 ~
  79.     count is 2 ~
  80.     count is 3 ~
  81.     count is 4 ~
  82.  
  83.     Note:
  84.     If you happen to write a while loop that keeps on running, you can
  85.     interrupt it by pressing CTRL-C (CTRL-Break on MS-Windows).
  86.  
  87.  
  88. THREE KINDS OF NUMBERS
  89.  
  90. Numbers can be decimal, hexadecimal or octal.  A hexadecimal number starts
  91. with "0x" or "0X".  For example "0x1f" is 31.  An octal number starts with a
  92. zero.  "017" is 15.  Careful: don't put a zero before a decimal number, it
  93. will be intepreted as an octal number!
  94.    The ":echo" command always prints decimal numbers.  Example: >
  95.  
  96.     :echo 0x7f 036
  97. <    127 30 ~
  98.  
  99. A number is made negative with a minus sign.  This also works for hexadecimal
  100. and octal numbers.   A minus sign is also for substraction.  Compare this with
  101. the previous example: >
  102.  
  103.     :echo 0x7f -036
  104. <    97 ~
  105.  
  106. White space in an expression is ignored.  However, it's recommended to use it
  107. for separating items, to make the expression easier to read.  For example, to
  108. avoid the confusion with a negative number, put a space between the minus sign
  109. and the following number: >
  110.  
  111.     :echo 0x7f - 036
  112.  
  113. ==============================================================================
  114. *41.2*    Variables
  115.  
  116. A variable name consists of ASCII letters, digits and the underscore.  It
  117. cannot start with a digit.  Valid variable names are:
  118.  
  119.     counter
  120.     _aap3
  121.     very_long_variable_name_with_dashes
  122.     FuncLength
  123.     LENGTH
  124.  
  125. Invalid names are "foo+bar" and "6var".
  126.    These variables are global.  To see a list of currently defined variables
  127. use this command: >
  128.  
  129.     :let
  130.  
  131. You can use global variables everywhere.  This also means that when the
  132. variable "count" is used in one script file, it might also be used in another
  133. file.  This leads to confusion at least, and real problems at worst.  To avoid
  134. this, you can use a variable local to a script file by prepending "s:".  For
  135. example, one script contains this code: >
  136.  
  137.     :let s:count = 1
  138.     :while s:count < 5
  139.     :  source other.vim
  140.     :  let s:count = s:count + 1
  141.     :endwhile
  142.  
  143. Since "s:count" is local to this script, you can be sure that sourcing the
  144. "other.vim" script will not change this variable.  If "other.vim" also uses an
  145. "s:count" variable, it will be a different copy, local to that script.  More
  146. about script-local variables here: |script-variable|.
  147.  
  148. There are more kinds of variables, see |internal-variables|.  The most often
  149. used ones are:
  150.  
  151.     b:name        variable local to a buffer
  152.     w:name        variable local to a window
  153.     g:name        global variable (also in a function)
  154.     v:name        variable predefined by Vim
  155.  
  156.  
  157. DELETING VARIABLES
  158.  
  159. Variables take up memory and show up in the output of the ":let" command.  To
  160. delete a variable use the ":unlet" command.  Example: >
  161.  
  162.     :unlet s:count
  163.  
  164. This deletes the script-local variable "s:count" to free up the memory it
  165. uses.  If you are not sure if the variable exists, and don't want an error
  166. message when it doesn't, append !: >
  167.  
  168.     :unlet! s:count
  169.  
  170. When a script finishes, the local variables used there will not be
  171. automatically freed.  The next time the script executes, it can still use the
  172. old value.  Example: >
  173.  
  174.     :if !exists("s:call_count")
  175.     :  let s:call_count = 0
  176.     :endif
  177.     :let s:call_count = s:call_count + 1
  178.     :echo "called" s:call_count "times"
  179.  
  180. The "exists()" function checks if a variable has already been defined.  Its
  181. argument is the name of the variable you want to check.  Not the variable
  182. itself!  If you would do this: >
  183.  
  184.     :if !exists(s:call_count)
  185.  
  186. Then the value of s:call_count will be used as the name of the variable that
  187. exists() checks.  That's not what you want.
  188.    The exclamation mark ! negates a value.  When the value was true, it
  189. becomes false.  When it was false, it becomes true.  You can read it as "not".
  190. Thus "if !exists()" can be read as "if not exists()".
  191.    What Vim calls true is anything that is not zero.  Only zero is false.
  192.  
  193.  
  194. STRING VARIABLES AND CONSTANTS
  195.  
  196. So far only numbers were used for the variable value.  Strings can be used as
  197. well.  Numbers and strings are the only two types of variables that Vim
  198. supports.  The type is dynamic, it is set each time when assigning a value to
  199. the variable with ":let".
  200.    To assign a string value to a variable, you need to use a string constant.
  201. There are two types of these.  First the string in double quotes: >
  202.  
  203.     :let name = "peter"
  204.     :echo name
  205. <    peter ~
  206.  
  207. If you want to include a double quote inside the string, put a backslash in
  208. front of it: >
  209.  
  210.     :let name = "\"peter\""
  211.     :echo name
  212. <    "peter" ~
  213.  
  214. To avoid the need for a backslash, you can use a string in single quotes: >
  215.  
  216.     :let name = '"peter"'
  217.     :echo name
  218. <    "peter" ~
  219.  
  220. Inside a single-quote string all the characters are taken literally.  The
  221. drawback is that it's impossible to include a single quote.  A backslash is
  222. taken literally as well, thus you can't use it to change the meaning of the
  223. character after it.
  224.    In double-quote strings it is possible to use special characters.  Here are
  225. a few useful ones:
  226.  
  227.     \t        <Tab>
  228.     \n        <NL>, line break
  229.     \r        <CR>, <Enter>
  230.     \e        <Esc>
  231.     \b        <BS>, backspace
  232.     \"        "
  233.     \\        \, backslash
  234.     \<Esc>        <Esc>
  235.     \<C-W>        CTRL-W
  236.  
  237. The last two are just examples.  The  "\<name>" form can be used to include
  238. the special key "name".
  239.    See |expr-quote| for the full list of special items in a string.
  240.  
  241. ==============================================================================
  242. *41.3*    Expressions
  243.  
  244. Vim has a rich, yet simple way to handle expressions.  You can read the
  245. definition here: |expression-syntax|.  Here we will show the most common
  246. items.
  247.    The numbers, strings and variables mentioned above are expressions by
  248. themselves.  Thus everywhere an expression is expected, you can use a number,
  249. string or variable.  Other basic items in an expression are:
  250.  
  251.     $NAME        environment variable
  252.     &name        option
  253.     @r        register
  254.  
  255. Examples: >
  256.  
  257.     :echo "The value of 'tabstop' is" &ts
  258.     :echo "Your home directory is" $HOME
  259.     :if @a > 5
  260.  
  261. The &option form can be used to save an option value, set it to a new value,
  262. do something and restore the old value.  Example: >
  263.  
  264.     :let save_ic = &ic
  265.     :set noic
  266.     :/The Start/,$delete
  267.     :let &ic = save_ic
  268.  
  269. This makes sure the "The Start" pattern is used with the 'ignorecase' option
  270. off.  Still, it keeps the value that the user had set.
  271.  
  272.  
  273. MATHEMATICS
  274.  
  275. It becomes more interesting if we combine these basic items.  Let's start with
  276. mathematics on numbers:
  277.  
  278.     a + b        add
  279.     a - b        subtract
  280.     a * b        multiply
  281.     a / b        divide
  282.     a % b        modulo
  283.  
  284. The usual precedence is used.  Example: >
  285.  
  286.     :echo 10 + 5 * 2
  287. <    20 ~
  288.  
  289. Grouping is done with braces.  No suprises here.  Example: >
  290.  
  291.     :echo (10 + 5) * 2
  292. <    30 ~
  293.  
  294. Strings can be concatenated with ".".  Example: >
  295.  
  296.     :echo "foo" . "bar"
  297. <    foobar ~
  298.  
  299. When the ":echo" command gets multiple arguments, it separates them with a
  300. space.  In the example the argument is a single expression, thus no space is
  301. inserted.
  302.  
  303. Borrowed from the C language is the conditional expression:
  304.  
  305.     a ? b : c
  306.  
  307. If "a" evaluates to true "b" is used, otherwise "c" is used.  Example: >
  308.  
  309.     :let i = 4
  310.     :echo i > 5 ? "i is big" : "i is small"
  311. <    i is small ~
  312.  
  313. The three parts of the constructs are always evaluated first, thus you could
  314. see it work as:
  315.  
  316.     (a) ? (b) : (c)
  317.  
  318. ==============================================================================
  319. *41.4*    Conditionals
  320.  
  321. The ":if" commands executes the following statements, until the matching
  322. ":endif", only when a condition is met.  The generic form is:
  323.  
  324.     :if {condition}
  325.        {statements}
  326.     :endif
  327.  
  328. Only when the expression {condition} evaluates to true (non-zero) will the
  329. {statements} be executed.  These must still be valid commands.  If they
  330. contain garbage, Vim won't be able to find the ":endif".
  331.    You can also use ":else".  The generic form for this is:
  332.  
  333.     :if {condition}
  334.        {statements}
  335.     :else
  336.        {statements}
  337.     :endif
  338.  
  339. The second {statements} is only executed if the first one isn't.
  340.    Finally, there is ":elseif":
  341.  
  342.     :if {condition}
  343.        {statements}
  344.     :elseif {condition}
  345.        {statements}
  346.     :endif
  347.  
  348. This works just like using ":else" and then "if", but without the need for an
  349. extra ":endif".
  350.    A useful example for your vimrc file is checking the 'term' option and
  351. doing something depending upon its value: >
  352.  
  353.     :if &term == "xterm"
  354.     :  " Do stuff for xterm
  355.     :elseif &term == "vt100"
  356.     :  " Do stuff for a vt100 terminal
  357.     :else
  358.     :  " Do something for other terminals
  359.     :endif
  360.  
  361.  
  362. LOGIC OPERATIONS
  363.  
  364. We already used some of them in the examples.  These are the most often used
  365. ones:
  366.  
  367.     a == b        equal to
  368.     a != b        not equal to
  369.     a >  b        greater than
  370.     a >= b        greater than or equal to
  371.     a <  b        less than
  372.     a <= b        less than or equal to
  373.  
  374. The result is one if the condition is met and zero otherwise.  An example: >
  375.  
  376.     :if v:version >= 600
  377.     :  echo "congratulations"
  378.     :else
  379.     :  echo "you are using an old version, upgrade!"
  380.     :endif
  381.  
  382. Here "v:version" is a variable defined by Vim, which has the value of the Vim
  383. version.  600 is for version 6.0.  Version 6.1 will have the value 601.
  384. This is very useful to write a script that works with multiple versions of
  385. Vim.  |v:version|
  386.  
  387. The logic operators work both for numbers and strings.  When comparing two
  388. strings, the mathematical difference is used.  This compares byte values,
  389. which may not be right for some languages.
  390.    When comparing a string with a number, the string is first converted to a
  391. number.  This is a bit tricky, because when a string doesn't look like a
  392. number, the number zero is used.  Example: >
  393.  
  394.     :if 0 == "one"
  395.     :  echo "yes"
  396.     :endif
  397.  
  398. This will echo "yes", because "one" doesn't look like a number, thus it is
  399. converted to the number zero.
  400.  
  401. For strings there are two more items:
  402.  
  403.     a =~ b        matches with
  404.     a !~ b        does not match with
  405.  
  406. The left item "a" is used as a string.  The right item "b" is used as a
  407. pattern, like what's used for searching.  Example: >
  408.  
  409.     :if str =~ " "
  410.     :  echo "str contains a space"
  411.     :elseif str !~ '\.$'
  412.     :  echo "str ends in a full stop"
  413.     :endif
  414.  
  415. Notice the use of a single-quote string for the pattern.  This is useful,
  416. because backslashes need to be doubled in a double-quote string and patterns
  417. tend to contain many backslashes.
  418.  
  419. The 'ignorecase' option is used when comparing strings.  When you don't want
  420. that, append "#" to match case and "?" to ignore case.  Thus "==?" compares
  421. two strings to be equal while ignoring case.  And "!~#" checks if a pattern
  422. doesn't match, also checking the case of letters.  For the full table see
  423. |expr-==|.
  424.  
  425.  
  426. MORE LOOPING
  427.  
  428. The ":while" command was already mentioned.  Two more statements can be used
  429. in between the ":while" and the ":endwhile":
  430.  
  431.     :continue        Jump back to the start of the while loop; the
  432.                 loop continues.
  433.     :break            Jump forward to the ":endwhile"; the loop is
  434.                 discontinued.
  435.  
  436. Example: >
  437.  
  438.     :while counter < 40
  439.     :  call do_something()
  440.     :  if skip_flag
  441.     :    continue
  442.     :  endif
  443.     :  if finished_flag
  444.     :    break
  445.     :  endif
  446.     :  sleep 50m
  447.     :endwhile
  448.  
  449. The ":sleep" command makes Vim take a nap.  The "50m" specifies fifty
  450. milliseconds.  Another example is ":sleep 4", which sleeps for four seconds.
  451.  
  452. ==============================================================================
  453. *41.5*    Executing an expression
  454.  
  455. So far the commands in the script were executed by Vim directly.  The
  456. ":execute" command allows executing the result of an expression.  This is a
  457. very powerful way to build commands and execute them.
  458.    An example is to jump to a tag, which is contained in a variable: >
  459.  
  460.     :execute "tag " . tag_name
  461.  
  462. The "." is used to concatenate the string "tag " with the value of variable
  463. "tag_name".  Suppose "tag_name" has the value "get_cmd", then the command that
  464. will be executed is: >
  465.  
  466.     :tag get_cmd
  467.  
  468. The ":execute" command can only execute colon commands.  The ":normal" command
  469. executes Normal mode commands.  However, its argument is not an expression but
  470. the literal command characters.  Example: >
  471.  
  472.     :normal gg=G
  473.  
  474. This jumps to the first line and formats all lines with the "=" operator.
  475.    To make ":normal" work with an expression, combine ":execute" with it.
  476. Example: >
  477.  
  478.     :execute "normal " . normal_commands
  479.  
  480. The variable "normal_commands" must contain the Normal mode commands.
  481.    Make sure that the argument for ":normal" is a complete command.  Otherwise
  482. Vim will run into the end of the argument and abort the command.  For example,
  483. if you start Insert mode, you must leave Insert mode as well.  This works: >
  484.  
  485.     :execute "normal Inew text \<Esc>"
  486.  
  487. This inserts "new text " in the current line.  Notice the use of the special
  488. key "\<Esc>".  This avoids having to enter a real <Esc> character in your
  489. script.
  490.  
  491. ==============================================================================
  492. *41.6*    Using functions
  493.  
  494. Vim defines many functions and provides a large amount of functionality that
  495. way.  A few examples will be given in this section.  You can find the whole
  496. list here: |functions|.
  497.  
  498. A function is called with the ":call" command.  The parameters are passed in
  499. between braces, separated by commas.  Example: >
  500.  
  501.     :call search("Date: ", "W")
  502.  
  503. This calls the search() function, with arguments "Date: " and "W".  The
  504. search() function uses its first argument as a search pattern and the second
  505. one as flags.  The "W" flag means the search doesn't wrap around the end of
  506. the file.
  507.  
  508. A function can be called in an expression.  Example: >
  509.  
  510.     :let line = getline(".")
  511.     :let repl = substitute(line, '\a', "*", "g")
  512.     :call setline(".", repl)
  513.  
  514. The getline() function obtains a line from the current file.  Its argument is
  515. a specification of the line number.  In this case "." is used, which means the
  516. line where the cursor.
  517.    The substitute() function does something similar to the ":substitute"
  518. command.  The first argument is the string on which to perform the
  519. substitution.  The second argument is the pattern, the third the replacement
  520. string.  Finally, the last arguments are the flags.
  521.    The setline() function sets the line, specified by the first argument, to a
  522. new string, the second argument.  In this example the line under the cursor is
  523. replaced with the result of the substitute().  Thus the effect of the three
  524. statements is equal to: >
  525.  
  526.     :substitute/\a/*/g
  527.  
  528. Using the functions becomes more interesting when you do more work before and
  529. after the substitute() call.
  530.  
  531.  
  532. FUNCTIONS                        *function-list*
  533.  
  534. There are many functions.  We will mention them here, grouped by what they are
  535. used for.  You can find an alphabetical list here: |functions|.  Use CTRL-] on
  536. the function name to jump to detailed help on it.
  537.  
  538. String manipulation:
  539.     char2nr()        get ASCII value of a character
  540.     nr2char()        get a character by its ASCII value
  541.     escape()        escape characters in a string with a '\'
  542.     strtrans()        translate a string to make it printable
  543.     tolower()        turn a string to lowercase
  544.     toupper()        turn a string to uppercase
  545.     match()            position where a pattern matches in a string
  546.     matchend()        position where a pattern match ends in a string
  547.     matchstr()        match of a pattern in a string
  548.     stridx()        first index of a short string in a long string
  549.     strridx()        last index of a short string in a long string
  550.     strlen()        length of a string
  551.     substitute()        substitute a pattern match with a string
  552.     submatch()        get a specific match in a ":substitute"
  553.     strpart()        get part of a string
  554.     expand()        expand special keywords
  555.     type()            type of a variable
  556.  
  557. Working with text in the current buffer:
  558.     byte2line()        get line number at a specific byte count
  559.     line2byte()        byte count at a specific line
  560.     col()            column number of the cursor or a mark
  561.     virtcol()        screen column of the cursor or a mark
  562.     line()            line number of the cursor or mark
  563.     wincol()        window column number of the cursor
  564.     winline()        window line number of the cursor
  565.     getline()        get a line from the buffer
  566.     setline()        replace a line in the buffer
  567.     append()        append {string} below line {lnum}
  568.     indent()        indent of a specific line
  569.     cindent()        indent according to C indenting
  570.     lispindent()        indent according to Lisp indenting
  571.     nextnonblank()        find next non-blank line
  572.     prevnonblank()        find previous non-blank line
  573.     search()        find a match for a pattern
  574.     searchpair()        find the other end of a start/skip/end
  575.  
  576. System functions and manipulation of files:
  577.     browse()        put up a file requester
  578.     glob()            expand wildcards
  579.     globpath()        expand wildcards in a number of directories
  580.     resolve()        find out where a shortcut points to
  581.     fnamemodify()        modify a file name
  582.     executable()        check if an executable program exists
  583.     filereadable()        check if a file can be read
  584.     isdirectory()        check if a directory exists
  585.     getcwd()        get the current working directory
  586.     getfsize()        get the size of a file
  587.     getftime()        get last modification time of a file
  588.     localtime()        get current time
  589.     strftime()        convert time to a string
  590.     tempname()        get the name of a temporary file
  591.     delete()        delete a file
  592.     rename()        rename a file
  593.     system()        get the result of a shell command
  594.     hostname()        name of the system
  595.  
  596. Buffers, windows and the argument list:
  597.     argc()            number of entries in the argument list
  598.     argidx()        current position in the argument list
  599.     argv()            get one entry from the argument list
  600.     bufexists()        check if a buffer exists
  601.     buflisted()        check if a buffer exists and is listed
  602.     bufloaded()        check if a buffer exists and is loaded
  603.     bufname()        get the name of a specific buffer
  604.     bufnr()            get the buffer number of a specific buffer
  605.     winnr()            get the window number for the current window
  606.     bufwinnr()        get the window number of a specific buffer
  607.     winbufnr()        get the buffer number of a specific window
  608.     getbufvar()        get a variable value from a specific buffer
  609.     setbufvar()        set a variable in a specific buffer
  610.     getwinvar()        get a variable value from a specific window
  611.     setwinvar()        set a variable in a specific buffer
  612.  
  613. Folding:
  614.     foldclosed()        check for a closed fold at a specific line
  615.     foldlevel()        check for the fold level at a specific line
  616.     foldtext()        generate the line displayed for a closed fold
  617.  
  618. Syntax highlighting:
  619.     hlexists()        check if a highlight group exists
  620.     hlID()            get ID of a highlight group
  621.     synID()            get syntax ID at a specific position
  622.     synIDattr()        get a specific attribute of a syntax ID
  623.     synIDtrans()        get translated syntax ID
  624.  
  625. History:
  626.     histadd()        add an item to a history
  627.     histdel()        delete an item from a history
  628.     histget()        get an item from a history
  629.     histnr()        get highest index of a history list
  630.  
  631. Interactive:
  632.     confirm()        let the user make a choice
  633.     getchar()        get a character from the user
  634.     getcharmod()        get modifiers for the last typed character
  635.     input()            get a line from the user
  636.     inputsecret()        get a line from the user without showing it
  637.     inputdialog()        get a line from the user in a dialog
  638.  
  639. Vim server:
  640.     serverlist()        return the list of server names
  641.     remote_send()        send command characters to a Vim server
  642.     remote_expr()        evaluate an expression in a Vim server
  643.     server2client()        send a reply to a client of a Vim server
  644.     remote_peek()        check if there is a reply from a Vim server
  645.     remote_read()        read a reply from a Vim server
  646.     foreground()        move the Vim window to the foreground
  647.     remote_foreground()    move the Vim server window to the foreground
  648.  
  649. Various:
  650.     mode()            get current editing mode
  651.     visualmode()        last visual mode used
  652.     hasmapto()        check if a mapping exists
  653.     mapcheck()        check if a matching mapping exists
  654.     maparg()        get rhs of a mapping
  655.     exists()        check if a variable, function, etc. exists
  656.     has()            check if a feature is supported in Vim
  657.     cscope_connection()    check if a cscope connection exists
  658.     did_filetype()        check if a FileType autocommand was used
  659.     eventhandler()        check if invoked by an event handler
  660.     getwinposx()        X position of the GUI Vim window
  661.     getwinposy()        Y position of the GUI Vim window
  662.     winheight()        get height of a specific window
  663.     winwidth()        get width of a specific window
  664.     libcall()        call a function in an external library
  665.     libcallnr()        idem, returning a number
  666.  
  667. ==============================================================================
  668. *41.7*    Defining a function
  669.  
  670. Vim enables you to define your own functions.  The basic function declaration
  671. begins as follows: >
  672.  
  673.     :function {name}({var1}, {var2}, ...)
  674.     :  {body}
  675.     :endfunction
  676. <
  677.     Note:
  678.     Function names must begin with a capital letter.
  679.  
  680. Let's define a short function to return the smaller of two numbers.  It starts
  681. with this line: >
  682.  
  683.     :function Min(num1, num2)
  684.  
  685. This tells Vim that the function is named "Min" and it takes two arguments:
  686. "num1" and "num2".
  687.    The first thing you need to do is to check to see which number is smaller:
  688.    >
  689.     :  if a:num1 < a:num2
  690.  
  691. The special prefix "a:" tells Vim that the variable is a function argument.
  692. Let's assign the variable smaller the value of the smallest number: >
  693.  
  694.     :  if a:num1 < a:num2
  695.     :    let smaller = a:num1
  696.     :  else
  697.     :    let smaller = a:num2
  698.     :  endif
  699.  
  700. The variable "smaller" is a local variable.  Variables used inside a function
  701. are local unless prefixed by something like "g:", "a:", or "s:".
  702.  
  703.     Note:
  704.     To access a global variable from inside a function you must prepend
  705.     "g:" to it.  Thus "g:count" inside a function is used for the global
  706.     variable "count", and "count" is another variable, local to the
  707.     function.
  708.  
  709. You now use the ":return" statement to return the smallest number to the user.
  710. Finally, you end the function: >
  711.  
  712.     :  return smaller
  713.     :endfunction
  714.  
  715. The complete function definition is as follows: >
  716.  
  717.     :function Min(num1, num2)
  718.     :  if a:num1 < a:num2
  719.     :    let smaller = a:num1
  720.     :  else
  721.     :    let smaller = a:num2
  722.     :  endif
  723.     :  return smaller
  724.     :endfunction
  725.  
  726. A user defined function is called in exactly the same way as a builtin
  727. function.  Only the name is different.  The Min function can be used like
  728. this: >
  729.  
  730.     :echo Min(5, 8)
  731.  
  732. Only now will the function be executed and the lines be interpreted by Vim.
  733. If there are mistakes, like using an undefined variable or function, you will
  734. now get an error message.  When defining the function these errors are not
  735. detected.
  736.  
  737. When a function reaches ":endfunction" or ":return" is used without an
  738. argument, the function returns zero.
  739.  
  740. To redefine a function that already exists, use the ! for the ":function"
  741. command: >
  742.  
  743.     :function!  Min(num1, num2, num3)
  744.  
  745.  
  746. USING A RANGE
  747.  
  748. The ":call" command can be given a line range.  This can have one of two
  749. meanings.  When a function has been defined with the "range" keyword, it will
  750. take care of the line range itself.
  751.   The function will be passed the variables "a:firstline" and "a:lastline".
  752. These will have the line numbers from the range the function was called with.
  753. Example: >
  754.  
  755.     :function Count_words() range
  756.     :  let n = a:firstline
  757.     :  let count = 0
  758.     :  while n <= a:lastline
  759.     :    let count = count + Wordcount(getline(n))
  760.     :  endwhile
  761.     :  echo "found " . count . " words"
  762.     :endfunction
  763.  
  764. You can call this function with: >
  765.  
  766.     :10,30call Count_words()
  767.  
  768. It will be executed once and echo the number of words.
  769.    The other way to use a line range is by defining a function without the
  770. "range" keyword.  The function will be called once for every line in the
  771. range, with the cursor in that line.  Example: >
  772.  
  773.     :function  Number()
  774.     :  echo "line " . line(".") . " contains: " . getline(".")
  775.     :endfunction
  776.  
  777. If you call this function with: >
  778.  
  779.     :10,15call Number()
  780.  
  781. The function will be called six times.
  782.  
  783.  
  784. VARIABLE NUMBER OF ARGUMENTS
  785.  
  786. Vim enables you to define functions that have a variable number of arguments.
  787. The following command, for instance, defines a function that must have 1
  788. argument (start) and can have up to 20 additional arguments: >
  789.  
  790.     :function Show(start, ...)
  791.  
  792. The variable "a:1" contains the first optional argument, "a:2" the second, and
  793. so on.  The variable "a:0" contains the number of extra arguments.
  794.    For example: >
  795.  
  796.     :function Show(start, ...)
  797.     :  echohl Title
  798.     :  echo "Show is " . a:start
  799.     :  echohl None
  800.     :  let index = 1
  801.     :  while index <= a:0
  802.     :    execute 'echon "  Arg " . index . " is " . a:' . index
  803.     :    let index = index + 1
  804.     :  endwhile
  805.     :  echo ""
  806.     :endfunction
  807.  
  808. This uses the ":echohl" command to specify the highlighting used for the
  809. following ":echo" command.  ":echohl None" stops it again.  The ":echon"
  810. command works like ":echo", but doesn't output a line break.
  811.  
  812.  
  813. LISTING FUNCTIONS
  814.  
  815. The ":function" command lists the names and arguments of all user-defined
  816. functions: >
  817.  
  818.     :function
  819. <    function Show(start, ...) ~
  820.     function GetVimIndent()~
  821.     function SetSyn(name) ~
  822.  
  823. To see what a function does, use its name as an argument for ":function": >
  824.  
  825.     :function Show
  826. <    1       :  echo "Show is " . a:start ~
  827.     2       :  let index = 1 ~
  828.     3       :  while index <= a:0 ~
  829.     4       :    execute 'echo "Arg " . index . " is " . a:' . index ~
  830.     5       :    let index = index + 1 ~
  831.     6       :  endwhile ~
  832.        endfunction ~
  833.  
  834.  
  835. DEBUGGING
  836.  
  837. The line number is useful for when you get an error message or when debugging.
  838. See |debug-scripts| about debugging mode.
  839.    You can also set the 'verbose' option to 12 or higher to see all function
  840. calls.  Set it to 15 or higher to see every executed line.
  841.  
  842.  
  843. DELETING A FUNCTION
  844.  
  845. To delete the Show() function: >
  846.  
  847.     :delfunction Show
  848.  
  849. You get an error when the function doesn't exist.
  850.  
  851. ==============================================================================
  852. *41.8*    Various remarks
  853.  
  854. Here is a summary of items that apply to Vim scripts.  They are also mentioned
  855. elsewhere, but form a nice checklist.
  856.  
  857. The end-of-line character depends on the system.  For Unix a single <NL>
  858. character is used.  For MS-DOS, Windows, OS/2 and the like, <CR><LF> is used.
  859. This is important when using mappings that end in a <CR>.  See |:source_crnl|.
  860.  
  861.  
  862. WHITE SPACE
  863.  
  864. Blank lines are allowed and ignored.
  865.  
  866. Leading whitespace characters (blanks and TABs) are always ignored.  The
  867. whitespaces between parameters (e.g. between the 'set' and the 'cpoptions' in the
  868. example below) are reduced to one blank character and plays the role of a
  869. separator, the whitespaces after the last (visible) character may or may not
  870. be ignored depending on the situation, see below.
  871.  
  872. For a ":set" command involving the "=" (equal) sign, such as in: >
  873.  
  874.     :set cpoptions    =aABceFst
  875.  
  876. The whitespace immediately before the "=" sign is ignored.  But there can be
  877. no whitespace after the "=" sign!
  878.  
  879. To include a whitespace character in the value of an option, it must be
  880. escaped by a "\" (backslash)  as in the following example: >
  881.  
  882.     :set tags=my\ nice\ file
  883.  
  884. The same example written as >
  885.  
  886.     :set tags=my nice file
  887.  
  888. will issue an error, because it is interpreted as: >
  889.  
  890.     :set tags=my
  891.     :set nice
  892.     :set file
  893.  
  894.  
  895. COMMENTS
  896.  
  897. The character " (the double quote mark) starts a comment.  Everything after
  898. and including this character until the end-of-line is considered a comment and
  899. is ignored, except for commands that don't consider comments, as shown in
  900. examples below.  A comment can start on any character position on the line.
  901.  
  902. There is a little "catch" with comments for some commands.  Examples: >
  903.  
  904.     :abbrev dev development        " shorthand
  905.     :map <F3> o#include        " insert include
  906.     :execute cmd            " do it
  907.     :!ls *.c            " list C files
  908.  
  909. The abbreviation 'dev' will be expanded to 'development     " shorthand'.  The
  910. mapping of <F3> will actually be the whole line after the 'o# ....' including
  911. the '" insert include'.  The "execute" command will give an error.  The "!"
  912. command will send everything after it to the shell, causing an error for an
  913. unmatched '"' character.
  914.    There can be no comment after ":map", ":abbreviate", ":execute" and "!"
  915. commands (there are a few more commands with this restriction).  For the
  916. "map", ":abbreviate" and "execute" commands there is a trick: >
  917.  
  918.     :abbrev dev development|" shorthand
  919.     :map <F3> o#include|" insert include
  920.     :execute cmd            |" do it
  921.  
  922. With the '|' character the command is separated from the next one.  And that
  923. next command is only a comment.
  924.  
  925. Notice that there is no white space before the '|' in the abbreviation and
  926. mapping.  For these commands, any character until the end-of-line or '|' is
  927. included.  As a consequence of this behavior, you don't always see that
  928. trailing whitespace is included: >
  929.  
  930.     :map <F4> o#include  
  931.  
  932. To avoid these problems, you can set the 'list' option when editing vimrc
  933. files.
  934.  
  935.  
  936. PITFALLS
  937.  
  938. Even bigger problem arises in the following example: >
  939.  
  940.     :map ,ab o#include
  941.     :unmap ,ab 
  942.  
  943. Here the unmap command will not work, because it tries to unmap ",ab ".  This
  944. does not exist as a mapped sequence.  An error will be issued, which is very
  945. hard to identify, because the ending whitespace character on the 'unmap ,ab '
  946. is not visible.
  947.  
  948. And this is the same as what happens when one uses a comment after an 'unmap'
  949. command: >
  950.  
  951.     :unmap ,ab     " comment
  952.  
  953. Here the comment part will be ignored.  However, Vim will try to unmap
  954. ',ab     ', which does not exist.  Rewreite it as: >
  955.  
  956.     :unmap ,ab|" comment
  957.  
  958.  
  959. RESTORING THE VIEW
  960.  
  961. Sometimes you want to make a change and go back to where cursor was.
  962. Restoring the relative position would also be nice, so that the same line
  963. appears at the top of the window.
  964.    This example yanks the current line, puts it above the first line in the
  965. file and then restores the view: >
  966.  
  967.     map ,p ma"aYHmbgg"aP`bzt`a
  968.  
  969. What this does: >
  970.     ma"aYHmbgg"aP`bzt`a
  971. <    ma            set mark a at cursor position
  972.       "aY            yank current line into register a
  973.          Hmb        go to top line in window and set mark b there
  974.         gg        go to first line in file
  975.           "aP        put the yanked line above it
  976.              `b        go back to top line in display
  977.                zt    position the text in the window as before
  978.              `a    go back to saved cursor position
  979.  
  980.  
  981. PACKAGING
  982.  
  983. To avoid your function names to interfere with functions that you get from
  984. others, use this scheme:
  985. - Prepend a unique string before each function name.  I often use an
  986.   abbreviation.  For example, "OW_" is used for the option window functions.
  987. - Put the definition of your functions together in a file.  Set a global
  988.   variable to indicate that the functions have been loaded.  When sourcing the
  989.   file again, first unload the functions.
  990. Example: >
  991.  
  992.     " This is the XXX package
  993.  
  994.     if exists("XXX_loaded")
  995.       delfun XXX_one
  996.       delfun XXX_two
  997.     endif
  998.  
  999.     function XXX_one(a)
  1000.         ... body of function ...
  1001.     endfun
  1002.  
  1003.     function XXX_two(b)
  1004.         ... body of function ...
  1005.     endfun
  1006.  
  1007.     let XXX_loaded = 1
  1008.  
  1009. ==============================================================================
  1010. *41.9*    Writing a plugin                *write-plugin*
  1011.  
  1012. You can write a Vim script in such a way that many people can use it.  This is
  1013. called a plugin.  Vim users can drop your script in their plugin directory and
  1014. use its features right away |add-plugin|.
  1015.  
  1016. There are actually two types of plugins:
  1017.  
  1018.   global plugins: For all types of files.
  1019. filetype plugins: Only for files of a specific type.
  1020.  
  1021. In this section the first type is explained.  Most items are also relevant for
  1022. writing filetype plugins.  The specifics for filetype plugins are in the next
  1023. section |write-filetype-plugin|.
  1024.  
  1025.  
  1026. NAME
  1027.  
  1028. First of all you must choose a name for your plugin.  The features provided
  1029. by the plugin should be clear from its name.  And it should be unlikely that
  1030. someone else writes a plugin with the same name but which does something
  1031. different.  And please limit the name to 8 characters, to avoid problems on
  1032. old Windows systems.
  1033.  
  1034. A script that corrects typing mistakes could be called "typecorr.vim".  We
  1035. will use it here as an example.
  1036.  
  1037. For the plugin to work for everybody, it should follow a few guidelines.  This
  1038. will be explained step-by-step.  The complete example plugin is at the end.
  1039.  
  1040.  
  1041. BODY
  1042.  
  1043. Let's start with the body of the plugin, the lines that do the actual work: >
  1044.  
  1045.  13    iabbrev teh the
  1046.  14    iabbrev otehr other
  1047.  15    iabbrev wnat want
  1048.  16    iabbrev synchronisation
  1049.  17        \ synchronization
  1050.  18    let s:count = 4
  1051.  
  1052. The actual list should be much longer, of course.
  1053.  
  1054. The line numbers have only been added to explain a few things, don't put them
  1055. in your plugin file!
  1056.  
  1057.  
  1058. HEADER
  1059.  
  1060. You will probably add new corrections to the plugin and soon have several
  1061. versions laying around.  And when distributing this file, people will want to
  1062. know who wrote this wonderful plugin and where they can send remarks.
  1063. Therefore, put a header at the top of your plugin: >
  1064.  
  1065.   1    " Vim global plugin for correcting typing mistakes
  1066.   2    " Last Change: 2000 Oct 15
  1067.   3    " Maintainer: Bram Moolenaar <Bram@vim.org>
  1068.  
  1069.  
  1070. LINE CONTINUATION, AVOIDING SIDE EFFECTS
  1071.  
  1072. In line 17 above, the line-continuation mechanism is used |line-continuation|.
  1073. Users with 'compatible' set will run into trouble here, they will get an error
  1074. message.  We can't just reset 'compatible', because that has a lot of side
  1075. effects.  To avoid this, we will set the 'cpoptions' option to its Vim default
  1076. value and restore it later.  That will allow the use of line-continuation and
  1077. make the script work for most people.  It is done like this: >
  1078.  
  1079.  10    let s:save_cpo = &cpo
  1080.  11    set cpo&vim
  1081.  ..
  1082.  41    let &cpo = s:save_cpo
  1083.  
  1084. We first store the old value of 'cpoptions' in the s:save_cpo variable.  At
  1085. the end of the plugin this value is restored.
  1086.  
  1087. Notice that a script-local variable is used |s:var|.  A global variable could
  1088. already be in use for something else.  Always use script-local variables for
  1089. things that are only used in the script.
  1090.  
  1091.  
  1092. NOT LOADING
  1093.  
  1094. It's possible that a user doesn't always want to load this plugin.  Or the
  1095. system administrator has dropped it in the system-wide plugin directory, but a
  1096. user has his own plugin he wants to use.  Then the user must have a chance to
  1097. disable loading this specific plugin.  This will make it possible: >
  1098.  
  1099.   5    if exists("loaded_typecorr")
  1100.   6      finish
  1101.   7    endif
  1102.   8    let loaded_typecorr = 1
  1103.  
  1104. This also avoids that when the script is loaded twice it would cause error
  1105. messages for redefining functions and cause trouble for autocommands that are
  1106. added twice.
  1107.  
  1108.  
  1109. MAPPING
  1110.  
  1111. Now let's make the plugin more interesting: We will add a mapping that adds a
  1112. correction for the word under the cursor.  We could just pick a key sequence
  1113. for this mapping, but the user might already use it for something else.  To
  1114. allow the user to define which keys a mapping in a plugin uses, the <Leader>
  1115. item can be used: >
  1116.  
  1117.  21      map <unique> <Leader>a  <Plug>TypecorrAdd
  1118.  
  1119. The "<Plug>TypecorrAdd" thing will do the work, more about that further on.
  1120.  
  1121. The user can set the "mapleader" variable to the key sequence that he wants
  1122. this mapping to start with.  Thus if the user has done: >
  1123.  
  1124.     let mapleader = "_"
  1125.  
  1126. the mapping will define "_a".  If the user didn't do this, the default value
  1127. will be used, which is a backslash.  Then a map for "\a" will be defined.
  1128.  
  1129. Note that <unique> is used, this will cause an error message if the mapping
  1130. already happened to exist. |:map-<unique>|
  1131.  
  1132. But what if the user wants to define his own key sequence?  We can allow that
  1133. with this mechanism: >
  1134.  
  1135.  20    if !hasmapto('<Plug>TypecorrAdd')
  1136.  21      map <unique> <Leader>a  <Plug>TypecorrAdd
  1137.  22    endif
  1138.  
  1139. This checks if a mapping to "<Plug>TypecorrAdd" already exists, and only
  1140. defines the mapping from "<Leader>a" if it doesn't.  The user then has a
  1141. chance of putting this in his vimrc file: >
  1142.  
  1143.     map ,c  <Plug>TypecorrAdd
  1144.  
  1145. Then the mapped key sequence will be ",c" instead of "_a" or "\a".
  1146.  
  1147.  
  1148. PIECES
  1149.  
  1150. If a script gets longer, you often want to break up the work in pieces.  You
  1151. can use functions or mappings for this.  But you don't want these functions
  1152. and mappings to interfere with the ones from other scripts.  For example, you
  1153. could define a function Add(), but another script could try to define the same
  1154. function.  To avoid this, we define the function local to the script by
  1155. prepending it with "s:".
  1156.  
  1157. We will define a function that adds a new typing correction: >
  1158.  
  1159.  29    function s:Add(from, correct)
  1160.  30      let to = input("type the correction for " . a:from . ": ")
  1161.  31      exe ":iabbrev " . a:from . " " . to
  1162.  ..
  1163.  35    endfunction
  1164.  
  1165. Now we can call the function s:Add() from within this script.  If another
  1166. script also defines s:Add(), it will be local to that script and can only
  1167. be called from the script it was defined in.  There can also be a global Add()
  1168. function (without the "s:"), which is again another function.
  1169.  
  1170. <SID> can be used with mappings.  It generates a script ID, which identifies
  1171. the current script.  In our typing correction plugin we use it like this: >
  1172.  
  1173.  23    noremap <unique> <script> <Plug>TypecorrAdd  <SID>Add
  1174.  ..
  1175.  27    noremap <SID>Add  :call <SID>Add(expand("<cword>"), 1)<CR>
  1176.  
  1177. Thus when a user types "\a", this sequence is invoked: >
  1178.  
  1179.     \a  ->  <Plug>TypecorrAdd  ->  <SID>Add  ->  :call <SID>Add()
  1180.  
  1181. If another script would also map <SID>Add, it would get another script ID and
  1182. thus define another mapping.
  1183.  
  1184. Note that instead of s:Add() we use <SID>Add() here.  That is because the
  1185. mapping is typed by the user, thus outside of the script.  The <SID> is
  1186. translated to the script ID, so that Vim knows in which script to look for
  1187. the Add() function.
  1188.  
  1189. This is a bit complicated, but it's required for the plugin to work together
  1190. with other plugins.  The basic rule is that you use <SID>Add() in mappings and
  1191. s:Add() in other places (the script itself, autocommands, user commands).
  1192.  
  1193. We can also add a menu entry to do the same as the mapping: >
  1194.  
  1195.  25    noremenu <script> Plugin.Add\ Correction      <SID>Add
  1196.  
  1197. The "Plugin" menu is recommended for adding menu items for plugins.  In this
  1198. case only one item is used.  When adding more items, creating a submenu is
  1199. recommended.  For example, "Plugin.CVS" could be used for a plugin that offers
  1200. CVS operations "Plugin.CVS.checkin", "Plugin.CVS.checkout", etc.
  1201.  
  1202. Note that in line 27 ":noremap" is used to avoid that any other mappings cause
  1203. trouble.  Someone may have remapped ":call", for example.  In line 23 we also
  1204. use ":noremap", but we do want "<SID>Add" to be remapped.  This is why
  1205. "<script>" is used here.  This only allows mappings which are local to the
  1206. script. |:map-<script>|  The same is done in line 25 for ":noremenu".
  1207. |:menu-<script>|
  1208.  
  1209.  
  1210. <SID> AND <Plug>
  1211.  
  1212. Both <SID> and <Plug> are used to avoid that mappings of typed keys interfere
  1213. with mappings that are only to be used from other mappings.  Note the
  1214. difference between using <SID> and <Plug>:
  1215.  
  1216. <Plug>    is visible outside of the script.  It is used for mappings which the
  1217.     user might want to map a key sequence to.  <Plug> is a special code
  1218.     that a typed key will never produce.
  1219.     To make it very unlikely that other plugins use the same sequence of
  1220.     characters, use this structure: <Plug> scriptname mapname
  1221.     In our example the scriptname is "Typecorr" and the mapname is "Add".
  1222.     This results in "<Plug>TypecorrAdd".  Only the first character of
  1223.     scriptname and mapname is uppercase, so that we can see where mapname
  1224.     starts.
  1225.  
  1226. <SID>    is the script ID, a unique identifier for a script.
  1227.     Internally Vim translates <SID> to "<SNR>123_", where "123" can be any
  1228.     number.  Thus a function "<SID>Add()" will have a name "<SNR>11_Add()"
  1229.     in one script, and "<SNR>22_Add()" in another.  You can see this if
  1230.     you use the ":function" command to get a list of functions.  The
  1231.     translation of <SID> in mappings is exactly the same, that's how you
  1232.     can call a script-local function from a mapping.
  1233.  
  1234.  
  1235. USER COMMAND
  1236.  
  1237. Now let's add a user command to add a correction: >
  1238.  
  1239.  37    if !exists(":Correct")
  1240.  38      command -nargs=1  Correct  :call s:Add(<q-args>, 0)
  1241.  39    endif
  1242.  
  1243. The user command is defined only if no command with the same name already
  1244. exists.  Otherwise we would get an error here.  Overriding the existing user
  1245. command with ":command!" is not a good idea, this would probably make the user
  1246. wonder why the command he defined himself doesn't work.  |:command|
  1247.  
  1248.  
  1249. SCRIPT VARIABLES
  1250.  
  1251. When a variable starts with "s:" it is a script variable.  It can only be used
  1252. inside a script.  Outside the script it's not visible  This avoids trouble
  1253. with using the same variable name in different scripts.  The variables will be
  1254. kept as long as Vim is running.  And the same variables are used when sourcing
  1255. the same script again. |s:var|
  1256.  
  1257. The fun is that these variables can also be used in functions, autocommands
  1258. and user commands that are defined in the script.  In our example we can add
  1259. a few lines to count the number of corrections: >
  1260.  
  1261.  18    let s:count = 4
  1262.  ..
  1263.  29    function s:Add(from, correct)
  1264.  ..
  1265.  33      let s:count = s:count + 1
  1266.  34      echo s:count . " corrections now"
  1267.  35    endfunction
  1268.  
  1269. First s:count is initialized to 4 in the script itself.  When later the
  1270. s:Add() function is called, it increments s:count.  It doesn't matter from
  1271. where the function was called, since it has been defined in the script, it
  1272. will use the local variables from this script.
  1273.  
  1274.  
  1275. THE RESULT
  1276.  
  1277. Here is the resulting complete example: >
  1278.  
  1279.   1    " Vim global plugin for correcting typing mistakes
  1280.   2    " Last Change: 2000 Oct 15
  1281.   3    " Maintainer: Bram Moolenaar <Bram@vim.org>
  1282.   4
  1283.   5    if exists("loaded_typecorr")
  1284.   6      finish
  1285.   7    endif
  1286.   8    let loaded_typecorr = 1
  1287.   9
  1288.  10    let s:save_cpo = &cpo
  1289.  11    set cpo&vim
  1290.  12
  1291.  13    iabbrev teh the
  1292.  14    iabbrev otehr other
  1293.  15    iabbrev wnat want
  1294.  16    iabbrev synchronisation
  1295.  17        \ synchronization
  1296.  18    let s:count = 4
  1297.  19
  1298.  20    if !hasmapto('<Plug>TypecorrAdd')
  1299.  21      map <unique> <Leader>a  <Plug>TypecorrAdd
  1300.  22    endif
  1301.  23    noremap <unique> <script> <Plug>TypecorrAdd  <SID>Add
  1302.  24
  1303.  25    noremenu <script> Plugin.Add\ Correction      <SID>Add
  1304.  26
  1305.  27    noremap <SID>Add  :call <SID>Add(expand("<cword>"), 1)<CR>
  1306.  28
  1307.  29    function s:Add(from, correct)
  1308.  30      let to = input("type the correction for " . a:from . ": ")
  1309.  31      exe ":iabbrev " . a:from . " " . to
  1310.  32      if a:correct | exe "normal viws\<C-R>\" \b\e" | endif
  1311.  33      let s:count = s:count + 1
  1312.  34      echo s:count . " corrections now"
  1313.  35    endfunction
  1314.  36
  1315.  37    if !exists(":Correct")
  1316.  38      command -nargs=1  Correct  :call s:Add(<q-args>, 0)
  1317.  39    endif
  1318.  40
  1319.  41    let &cpo = s:save_cpo
  1320.  
  1321. Line 32 wasn't explained yet.  It applies the new correction to the word under
  1322. the cursor.  The |:normal| command is used to use the new abbreviation.  Note
  1323. that mappings and abbreviations are expanded here, even though the function
  1324. was called from a mapping defined with ":noremap".
  1325.  
  1326.  
  1327. DOCUMENTATION
  1328.                             *write-local-help*
  1329. It's a good idea to also write some documentation for your plugin.  Especially
  1330. when its behavior can be changed by the user.  See |add-local-help| for how
  1331. they are installed.
  1332.  
  1333. Here is a simple example for a plugin help file, called "typecorr.txt": >
  1334.  
  1335.   1    *typecorr.txt*    Plugin for correcting typing mistakes
  1336.   2
  1337.   3    If you make typing mistakes, this plugin will have them corrected
  1338.   4    automatically.
  1339.   5
  1340.   6    There are currently only a few corrections.  Add your own if you like.
  1341.   7
  1342.   8    Mappings:
  1343.   9    <Leader>a   or   <Plug>TypecorrAdd
  1344.  10        Add a correction for the word under the cursor.
  1345.  11
  1346.  12    Commands:
  1347.  13    :Correct {word}
  1348.  14        Add a correction for {word}.
  1349.  15
  1350.  16                            *typecorr-settings*
  1351.  17    This plugin doesn't have any settings.
  1352.  
  1353. The first line is actually the only one for which the format matters.  It will
  1354. be extracted from the help file to be put in the "LOCAL ADDITIONS:" section of
  1355. help.txt.  The first "*" must be in the first column of the first line.
  1356.  
  1357. You can add more tags inside ** in your help file.  But be careful not to use
  1358. existing help tags.  You would probably use the name of your plugin in most of
  1359. them, like "typecorr-settings" in the example.
  1360.  
  1361. Using references to other parts of the help in || is recommended.  This makes
  1362. it easy for the user to find associated help.
  1363.  
  1364.  
  1365. SUMMARY                            *plugin-special*
  1366.  
  1367. Summary of special things to use in a plugin:
  1368.  
  1369. s:name            Variables local to the script.
  1370.  
  1371. <SID>            Script-ID, used for mappings and functions local to
  1372.             the script.
  1373.  
  1374. hasmapto()        Function to test if the user already defined a mapping
  1375.             for functionality the script offers.
  1376.  
  1377. <Leader>        Value of "mapleader", which the user defines as the
  1378.             keys that plugin mappings start with.
  1379.  
  1380. :map <unique>        Give a warning if a mapping already exists.
  1381.  
  1382. :noremap <script>    Use only mappings local to the script, not global
  1383.             mappings.
  1384.  
  1385. exists(":Cmd")        Check if a user command already exists.
  1386.  
  1387. ==============================================================================
  1388. *41.10*    Writing a filetype plugin    *write-filetype-plugin* *ftplugin*
  1389.  
  1390. A filetype plugin is like a global plugin, except that it sets options and
  1391. defines mappings for the current buffer only.  See |add-filetype-plugin| for
  1392. how this type of plugin is used.
  1393.  
  1394. First read the section on global plugins above |41.7|.  All that is said there
  1395. also applies to filetype plugins.  There are a few extras, which are explained
  1396. here.  The essential thing is that a filetype plugin should only have an
  1397. effect on the current buffer.
  1398.  
  1399.  
  1400. DISABLING
  1401.  
  1402. If you are writing a filetype plugin to be used by many people, they need a
  1403. chance to disable loading it.  Put this at the top of the plugin: >
  1404.  
  1405.     " Only do this when not done yet for this buffer
  1406.     if exists("b:did_ftplugin")
  1407.       finish
  1408.     endif
  1409.     let b:did_ftplugin = 1
  1410.  
  1411. This also needs to be used to avoid that the same plugin is executed twice for
  1412. the same buffer (happens when using an ":edit" command without arguments).
  1413.  
  1414. Now users can disable loading the default plugin completely by making a filetype
  1415. plugin with only this line: >
  1416.  
  1417.     let b:did_ftplugin = 1
  1418.  
  1419. This does require that the filetype plugin directory comes before $VIMRUNTIME
  1420. in 'runtimepath'!
  1421.  
  1422. If you do want to use the default plugin, but overrule one of the settings,
  1423. you can make a filetype plugin like this: >
  1424.  
  1425.     source $VIMRUNTIME/ftplugin/vim.vim
  1426.     set textwidth=70
  1427.  
  1428. This first loads the default filetype plugin to get all its settings.  Then
  1429. the value for the 'textwidth' option is changed to "70".  Note that the
  1430. default plugin will have set "b:did_ftplugin", thus when it's sourced later,
  1431. it won't do anything.
  1432.  
  1433.  
  1434. OPTIONS
  1435.  
  1436. To make sure the filetype plugin only affects the current buffer use the >
  1437.     :setlocal
  1438. command to set options.  And only set options which are local to a buffer (see
  1439. the help for the option to check that).  When using |:setlocal| for global
  1440. options or options local to a window, the value will change for many buffers,
  1441. and that is not what a filetype plugin should do.
  1442.  
  1443. When an option has a value that is a list of flags or items, consider using
  1444. "+=" and "-=" to keep the existing value.  Be aware that the user may have
  1445. changed an option value already.  First resetting to the default value and
  1446. then changing it often a good idea.  Example: >
  1447.     :setlocal formatoptions& formatoptions+=ro
  1448.  
  1449.  
  1450. MAPPINGS
  1451.  
  1452. To make sure mappings will only work in the current buffer use the >
  1453.     :map <buffer>
  1454. command.  This needs to be combined with the two-step mapping explained above.
  1455. An example of how to define funcionality in a filetype plugin: >
  1456.  
  1457.     if !hasmapto('<Plug>JavaImport')
  1458.       map <buffer> <unique> <LocalLeader>i <Plug>JavaImport
  1459.     endif
  1460.     noremap <buffer> <unique> <Plug>JavaImport oimport ""<Left><Esc>
  1461.  
  1462. |hasmapto()| is used to check if the user has already defined a map to
  1463. <Plug>JavaImport.  If not, then the filetype plugin defines the default
  1464. mapping.  This starts with |<LocalLeader>|, which allows the user to select
  1465. the key(s) he wants filetype plugin mappings to start with.  The default is a
  1466. backslash.
  1467. "<unique>" is used to give an error message if the mapping already exists or
  1468. overlaps with an existing mapping.
  1469. |:noremap| is used to avoid that any other mappings that the user has defined
  1470. interferes.  You might want to use ":noremap <script>" to allow remapping
  1471. mappings defined in this script that start with <SID>.
  1472.  
  1473. The user must have a chance to disable the mappings in a filetype plugin,
  1474. without disabling everything.  Here is an example of how this is done for a
  1475. plugin for the mail filetype: >
  1476.  
  1477.     " Add mappings, unless the user didn't want this.
  1478.     if !exists("no_plugin_maps") && !exists("no_mail_maps")
  1479.       " Quote text by inserting "> "
  1480.       if !hasmapto('<Plug>MailQuote')
  1481.         vmap <buffer> <LocalLeader>q <Plug>MailQuote
  1482.         nmap <buffer> <LocalLeader>q <Plug>MailQuote
  1483.       endif
  1484.       vnoremap <buffer> <Plug>MailQuote :s/^/> /<CR>
  1485.       nnoremap <buffer> <Plug>MailQuote :.,$s/^/> /<CR>
  1486.     endif
  1487.  
  1488. Two global variables are used:
  1489. no_plugin_maps        disables mappings for all filetype plugins
  1490. no_mail_maps        disables mappings for a specific filetype
  1491.  
  1492.  
  1493. USER COMMANDS
  1494.  
  1495. To add a user command for a specific file type, so that it can only be used in
  1496. one buffer, use the "-buffer" argument to |:command|.  Example: >
  1497.  
  1498.     :command -buffer  Make  make %:r.s
  1499.  
  1500.  
  1501. VARIABLES
  1502.  
  1503. A filetype plugin will be sourced for each buffer of the type it's for.  Local
  1504. script variables |s:var| will be shared between all invocations.  Use local
  1505. buffer variables |b:var| if you want a variable specifically for one buffer.
  1506.  
  1507.  
  1508. FUNCTIONS
  1509.  
  1510. When defining a function, this only needs to be done once.  But the filetype
  1511. plugin will be sourced every time a file with this filetype will be opened.
  1512. This construct make sure the function is only defined once: >
  1513.  
  1514.     :if !exists("*s:Func")
  1515.     :  function s:Func(arg)
  1516.     :    ...
  1517.     :  endfunction
  1518.     :endif
  1519. <
  1520.  
  1521. SUMMARY                            *ftplugin-special*
  1522.  
  1523. Summary of special things to use in a filetype plugin:
  1524.  
  1525. <LocalLeader>        Value of "maplocalleader", which the user defines as
  1526.             the keys that filetype plugin mappings start with.
  1527.  
  1528. :map <buffer>        Define a mapping local to the buffer.
  1529.  
  1530. :noremap <script>    Only remap mappings defined in this script that start
  1531.             with <SID>.
  1532.  
  1533. :setlocal        Set an option for the current buffer only.
  1534.  
  1535. :command -buffer    Define a user command local to the buffer.
  1536.  
  1537. exists("*s:Func")    Check if a function was already defined.
  1538.  
  1539. Also see |plugin-special|, the special things used for all plugins.
  1540.  
  1541. ==============================================================================
  1542. *41.11*    Writing a compiler plugin        *write-compiler-plugin*
  1543.  
  1544. A compiler plugin sets options for use with a specific compiler.  The user can
  1545. load it with the |:compiler| command.  The main use is to set the
  1546. 'errorformat' and 'makeprg' options.
  1547.  
  1548. The only special item about these files is a mechanism to allow a user to
  1549. overrule or add to the default file.  The default files start with: >
  1550.  
  1551.     :if exists("current_compiler")
  1552.     :  finish
  1553.     :endif
  1554.     :let current_compiler = "mine"
  1555.  
  1556. When you write a compiler file and put it in your personal runtime directory
  1557. (e.g., ~/.vim/runtime/compiler for Unix), you set the "current_compiler"
  1558. variable to make the default file skip the settings.
  1559.  
  1560. When you write a compiler plugin for the Vim distribution or for a system-wide
  1561. runtime directory, use the mechanism mentioned above.  When
  1562. "current_compiler" was already set by a user plugin nothing will be done.
  1563.  
  1564. When you write a compiler plugin to overrule settings from a default plugin,
  1565. don't check "current_compiler".  This plugin is supposed to be loaded
  1566. last, thus it should be in a directory at the end of 'runtimepath'.  For Unix
  1567. that could be ~/.vim/runtime/after/compiler.
  1568.  
  1569. ==============================================================================
  1570.  
  1571. Next chapter: |usr_42.txt|  Add new menus
  1572.  
  1573. Copyright: see |manual-copyright|  vim:tw=78:ts=8:ft=help:norl:
  1574.